package com.rzt.cft.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rzt.cft.constant.UserConstants;
import com.rzt.cft.utils.CustomUtil;
import com.rzt.cft.dto.sys.SysUserDto;
import com.rzt.cft.entity.sys.SysUser;
import com.rzt.cft.entity.sys.SysUserJob;
import com.rzt.cft.mapper.sys.SysUserJobMapper;
import com.rzt.cft.mapper.sys.SysUserMapper;
import com.rzt.cft.param.sys.SysUserJobParam;
import com.rzt.cft.service.sys.ISysUserService;
import com.rzt.cft.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 系统-后台用户 服务实现类
 * </p>
 *
 * @author zhongzhong
 * @since 2019-12-31
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserJobMapper sysUserJobMapper;


    @Transactional
    @Override
    public Boolean addUser(SysUserDto userDto) {
        SysUser user = CustomUtil.maping(userDto, SysUser.class);
        //密码处理
        String salt = ShiroUtils.getSalt();
//        String encodePasswd = PasswdUtils.get(user.getUserPwd(), salt);
        String encodePasswd = ShiroUtils.sha256(user.getUserPwd(), salt);
        user.setSalt(salt);
        user.setUserPwd(encodePasswd);
        user.setStatus(UserConstants.NORMAL);

        //插入用户
        int count = baseMapper.insert(user);
//        SysUserJob userJob = new SysUserJob();
////        userJob.setJobId(userDto.getJob().getId());
////        userJob.setUserId(user.getId());
////        //查询人岗位关联
////        sysUserJobMapper.insert(userJob);
        return retBool(count);
    }

    @Transactional
    @Override
    public boolean allotUserJob(SysUserJobParam userJobDto) {
        SysUserJob dbModel = CustomUtil.maping(userJobDto, SysUserJob.class);
        // 获取原有数据
        QueryWrapper<SysUserJob> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userJobDto.getUserId());
        List<SysUserJob> oldList = sysUserJobMapper.selectList(queryWrapper);
        List<String> didList = CustomUtil.select(oldList, SysUserJob::getId);
        if (oldList.size() > 0) {
            sysUserJobMapper.deleteBatchIds(didList);
        }
        int count = sysUserJobMapper.insert(dbModel);
        return retBool(count);
    }

}
